package com.example.myshopping3.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.myshopping3.model.Car;
import com.example.myshopping3.model.Result;
import com.example.myshopping3.model.view.CarView;
import com.example.myshopping3.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/car")
public class CarController {

    @Autowired
    private CarService carService;

    /**
     * 添加购物车功能
     * @param car
     * @return
     */
    @PostMapping("/addCar")
    public Result addCar(@RequestBody Car car){
        try{
            carService.addCar(car);
            return Result.success("添加成功",null);
        }catch(Exception ex){
            return Result.failt(500,"添加失败",null);
        }
    }

    /**
     * 根据用户id查询购物功能
     * @param userId
     * @return
     */
    @GetMapping("/getCarByUser/{userId}")
    public List<CarView> getCarByUser(@PathVariable int userId){
        List<CarView> carViewList = carService.getCarInfo(userId);
        System.out.println(carViewList);
        return carViewList;
    }

    /**
     * 删除购物车
     * @param carId
     * @return
     */
    @DeleteMapping("/deleteCar/{carId}")
    public Result deleteCar(@PathVariable Long carId){
        System.out.println(carId);
        carService.removeById(carId);
        return Result.success("删除成功",null);
    }

    /**
     * 批量删除购物车功能
     * @param carIds
     * @return
     */
    @DeleteMapping("/delCarBach")
    public Result delCarBach(String[] carIds){
        List<String> idsList = Arrays.asList(carIds);
        carService.removeBatchByIds(idsList);
        return Result.success("删除成功",null);
    }

    /**
     * 更新购物车
     * @param carId
     * @param carCount
     * @return
     */
    @PutMapping("/updateCarCount/{carId}/{carCount}")
    public Result updateCarCount(@PathVariable String carId,@PathVariable int carCount){
        UpdateWrapper<Car> updateWrapper  = new UpdateWrapper<>();
        updateWrapper.set("car_count",carCount).eq("car_id",carId);
        carService.update(updateWrapper);
        return Result.success("修改成功",null);
    }
}
